//
//  RYMessageViewController.m
//  League
//
//  Created by 崔璨 on 2018/1/24.
//  Copyright © 2018年 ciyuanjuzhen. All rights reserved.
//

#import "RYMessageViewController.h"
#import "HeadUserInfoView.h"
#import "OthersProfileViewController.h"
#import "IQKeyboardManager.h"
#import "AddEventViewController.h"
#import "UserInfomation.h"
#import "MemberListViewController.h"

#define kHeadViewH 110
@interface RYMessageViewController ()<RCChatSessionInputBarControlDelegate>
@property(strong , nonatomic)HeadUserInfoView *headV;
@end

@implementation RYMessageViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [IQKeyboardManager sharedManager].enable = NO;
    
    //expired不可聊天
    if(self.index == 1){
        self.chatSessionInputBarControl.userInteractionEnabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
//    self.conversationMessageCollectionView.frame =
    // Do any additional setup after loading the view.
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    [self listView];
    
    if (@available(iOS 11.0, *)) {
        self.conversationMessageCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    
//    RCUserInfo *info = [[RCUserInfo alloc] initWithUserId:@"ctest3" name:@"3333" portrait:@""];
//    com
//    [[RCIM sharedRCIM] refreshUserInfoCache:info withUserId:info.userId];
//
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}
/*点击系统键盘的语音按钮，导致输入工具栏被遮挡*/
- (void)keyboardWillShowNotification:(NSNotification *)notification {
    if(!self.chatSessionInputBarControl.inputTextView.isFirstResponder)
    {
        [self.chatSessionInputBarControl.inputTextView becomeFirstResponder];
    }
}
- (void)willDisplayConversationTableCell:(RCMessageBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath

{

    if ([cell isKindOfClass:[RCMessageCell class]]) {

        RCMessageCell *messageCell = (RCMessageCell *)cell;

        //messageCell.portraitImageView

        UIImageView *portraitImageView= (UIImageView *)messageCell.portraitImageView;

        portraitImageView.layer.cornerRadius = portraitImageView.height/2;

    }


    //    textCell.textLabel.
    
}


-(void)listView
{
    self.headV = [[HeadUserInfoView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, kHeadViewH)];
    [self.headV.backBtn addTarget:self action:@selector(backBtn:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview: self.headV];
    ConversionModel *model = self.model;
    self.headV.nameLab.text = model.name;
    
    //infoOne infoTwo
    NSString *infoStr = @"";
    NSString *schoolStr = @"";
    NSString *MembersStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Members" : @"成员";
    NSString *FriendsStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Friends" : @"好友";
    NSString *MatchsInGroupStr = [[InternationalControl userLanguage] isEqual:@"en"] ? @"MatchsInGroup" : @"相配";
    if(self.index <= 2){
        infoStr = [NSString stringWithFormat:@"%ld·%@·%ld", model.age, model.location, model.height];
        schoolStr = model.education;
    }
    else if(self.index == 3){
        infoStr = model.joinedTime;
        schoolStr = [NSString stringWithFormat:@"%@ %@", model.memberCount, MembersStr];
    }
    else{
        infoStr = model.about;
        schoolStr = [NSString stringWithFormat:@"%@ %@·%@ %@·%@ %@", model.size, MembersStr, model.friendCount, FriendsStr, model.matchesInGroupCount, MatchsInGroupStr];
    }
    self.headV.infoOne.text = infoStr;
    self.headV.infoTwo.text = schoolStr;
    [self.headV.headImage sd_setImageWithURL:[NSURL URLWithString:model.photoUrl] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction)];
    [self.headV.headImage addGestureRecognizer:singleTap];
    if(self.index > 2){
        self.headV.moreBtn.hidden = NO;
        [self.headV.moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    CGRect tableFrame = self.conversationMessageCollectionView .frame;
    tableFrame.origin.y = self.headV.height;
//    tableFrame.size.height = 100;
    self.conversationMessageCollectionView.frame = tableFrame;
    
    
    self.chatSessionInputBarControl.delegate = self;
//    []
   
//    CGRect tableFrame1 = self.chatSessionInputBarControl.frame;
//    tableFrame1.origin.y = tableFrame1.origin.y-100;
//    tableFrame1.size.width = 100;
//    self.chatSessionInputBarControl.frame = tableFrame1;
//    self.conversationMessageCollectionView.backgroundColor = [UIColor redColor];
    
    
    //自定义空会话的背景View。当会话列表为空时，将显示该View
    
    //UIView *blankView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    
    //blankView.backgroundColor=[UIColor redColor];
    
    //self.emptyConversationView=blankView;
    
}

-(void)singleTapAction
{
    if(self.index <= 2){
        UserProfileViewController *VC = [[UserProfileViewController alloc] init];
        VC.memberId = self.model.pk;
        VC.isMemberList = YES;
        [self.navigationController pushViewController:VC animated:YES];
    }
    else {
        FirstViewController *VC = [[FirstViewController alloc] init];
        VC.state = self.index == 3 ? EventDetailState : GroupDetailState;
        VC._id = self.model.pk;
        VC.title = self.model.name;
        [self.navigationController pushViewController:VC animated:YES];
    }
}
-(void)backBtn:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)didTapCellPortrait:(NSString *)userId
{
    NSLog(@"点击头像的id:%@",userId);
    OthersProfileViewController *otherProVc = [[OthersProfileViewController alloc] init];
    [self.navigationController pushViewController:otherProVc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - click
- (void)moreBtnClick {
    if(!self.model.conversation){
        return;
    }
    [[RCIMClient sharedRCIMClient] getConversationNotificationStatus:ConversationType_GROUP targetId:self.model.rongyun_id success:^(RCConversationNotificationStatus nStatus) {
        if(self.index == 3){
            [self loadEventAlert:nStatus];
        }
        else{
            [self loadGroupAlert:nStatus];
        }
    } error:^(RCErrorCode status) {
        
    }];
    
}

- (void)loadEventAlert:(RCConversationNotificationStatus)nStatus {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if(alert.popoverPresentationController){
        alert.popoverPresentationController.sourceView = self.headV.moreBtn;
        alert.popoverPresentationController.sourceRect = self.headV.moreBtn.bounds;
    }
    
    NSString *action1Str;
    if(nStatus == NOTIFY){
        action1Str = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Turn Off Chat Notifications" : @"关闭推送";
    }
    else{
        action1Str = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Turn On Chat Notifications" : @"开启推送";
    }
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:action1Str style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[RCIMClient sharedRCIMClient] setConversationNotificationStatus:ConversationType_GROUP targetId:self.model.rongyun_id isBlocked:nStatus == NOTIFY ? YES : NO success:^(RCConversationNotificationStatus nStatus) {
            NSLog(@"setConversationNotificationStatus-nStatus:%@", @(nStatus));
        } error:^(RCErrorCode status) {
            NSLog(@"setConversationNotificationStatus-error:%@", @(status));
        }];
    }];
    [alert addAction:action1];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:[[InternationalControl userLanguage] isEqual:@"en"] ? @"Leave Event" : @"离开聚一聚" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self leaveGroup];
    }];
    [alert addAction:action2];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action3];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    });
}
- (void)loadGroupAlert:(RCConversationNotificationStatus)nStatus {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if(alert.popoverPresentationController){
        alert.popoverPresentationController.sourceView = self.headV.moreBtn;
        alert.popoverPresentationController.sourceRect = self.headV.moreBtn.bounds;
    }
    
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:[[InternationalControl userLanguage] isEqual:@"en"] ? @"Promote Event to Group" : @"创建聚一聚" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self creatEvent];
    }];
    [alert addAction:action0];
    
    NSString *action1Str;
    if(nStatus == NOTIFY){
        action1Str = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Turn Off Chat Notifications" : @"关闭推送";
    }
    else{
        action1Str = [[InternationalControl userLanguage] isEqual:@"en"] ? @"Turn On Chat Notifications" : @"开启推送";
    }
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:action1Str style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[RCIMClient sharedRCIMClient] setConversationNotificationStatus:ConversationType_GROUP targetId:self.model.rongyun_id isBlocked:nStatus == NOTIFY ? YES : NO success:^(RCConversationNotificationStatus nStatus) {
            NSLog(@"setConversationNotificationStatus-nStatus:%@", @(nStatus));
        } error:^(RCErrorCode status) {
            NSLog(@"setConversationNotificationStatus-error:%@", @(status));
        }];
    }];
    [alert addAction:action1];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:[[InternationalControl userLanguage] isEqual:@"en"] ? @"Leave Event" : @"离开聊一聊" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self leaveGroup];
    }];
    [alert addAction:action2];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action3];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    });
}


/**
 离开 Event／Group
 */
- (void)leaveGroup {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定离开？" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSDictionary *dic = @{
                              @"pk1": self.model.pk,
                              @"pk2": [UserInfomation shareManager].pk
                              };
        NSString *apiStr = @"/customer/leaveGroup";
        if(self.index == 3){
            apiStr = @"/customer/leaveEvent";
        }
        NSLog(@"%@-params:%@", apiStr, dic);
        NSString *urlStr = [NSString stringWithFormat:@"%@%@", kFirstUrl, apiStr];
        [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
            
            NSLog(@"%@-backDic:%@", apiStr, backDic);
            if ([backDic[@"returnCode"] integerValue] == 200) {
                
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [SVProgressHUD showErrorWithStatus:backDic[@"msg"]];
            }
        } requestFail:^(NSString *backErrorStr) {
            [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
            NSLog(@"%@-backErrorStr:%@", apiStr, backErrorStr);
            
        }];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
}

/**
 创建 Event
 */
- (void)creatEvent {
    AddEventViewController *VC = [[AddEventViewController alloc] init];
    VC.groupId = self.model.pk;
    [self.navigationController pushViewController:VC animated:YES];
}
@end
